//
//  WCG_O_MapViewController.m
//  Project_B
//
//  Created by 黑黑 on 15/12/1.
//  Copyright © 2015年 Atom_Wang. All rights reserved.
//

#import "WCG_O_MapViewController.h"
//#import <MAMapKit/MAMapKit.h>
#import <AMapNaviKit/AMapNaviKit.h>
#import "MAMapKit.h"
#import <AMapLocationKit/AMapLocationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
//#import "InvertGeoDetailViewController.h"
//#import "ReGeocodeAnnotation.h"
#import "CommonUtility.h"
//#import "MANaviAnnotationView.h"
#import "BusLineViewController.h"
#import "BusLineDetailViewController.h"
#import "CommonUtility.h"
#import "BusStopAnnotation.h"
#import "BusStopDetailViewController.h"
#import "APIKey.h"
#import "HZL_MapViewController.h"
// 自定义annotation
#import "MANaviAnnotationView.h"
// POI
#import "GeoDetailViewController.h"
#import "AMapTipAnnotation.h"
#import "BusStopAnnotation.h"
#import "POIAnnotation.h"
#import "PoiDetailViewController.h"
#import "TipDetailViewController.h"

#define RightCallOutTag 1
#define LeftCallOutTag 2
#define BusLinePlaceHolder @"大连公交线路名称"
#define BusLinePaddingEdge 20

@interface WCG_O_MapViewController () <MAMapViewDelegate, AMapLocationManagerDelegate, UISearchBarDelegate, UISearchDisplayDelegate, UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) AMapLocationManager *locationManager;
@property (nonatomic, copy) AMapLocatingCompletionBlock completionBlock;

@property (nonatomic, strong) MAPointAnnotation *pointAnnotaiton;
@property (nonatomic, strong) CLLocation *location;

@property (nonatomic, assign) BOOL isDragging;
@property (nonatomic, assign) BOOL isSearchFromDragging;
//@property (nonatomic, strong) ReGeocodeAnnotation *annotation;

@property (nonatomic, strong) MAAnnotationView *userLocationAnnotationView;

// searchBar(bus)
@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) UIBarButtonItem *previousItem;
@property (nonatomic, strong) UIBarButtonItem *nextItem;
@property (nonatomic, strong) UIBarButtonItem *detailItem;
@property (nonatomic, strong) NSMutableArray *busLines;
@property (nonatomic, assign) NSInteger currentIndex;

// button
@property (nonatomic, strong) UIButton *locationBtn;
@property (nonatomic, strong) UIButton *busBtn;
@property (nonatomic, strong) UIButton *poiBtn;
@property (nonatomic, assign) BOOL bus;

// POISearch
@property (nonatomic, strong) UISearchDisplayController *displayController;

@property (nonatomic, strong) NSMutableArray *tips;
@end

@implementation WCG_O_MapViewController
@synthesize searchBar    = _searchBar;
@synthesize previousItem = _previousItem;
@synthesize nextItem     = _nextItem;
@synthesize detailItem   = _detailItem;

@synthesize busLines = _busLines;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    // 地图初始化
    [AMapLocationServices sharedServices].apiKey = (NSString *)APIKey;
    self.navigationController.navigationBarHidden = NO;
    self.locationManager = [[AMapLocationManager alloc] init];
    self.locationManager.delegate = self;
#if 0
    [self.locationManager startUpdatingLocation];
    [self configLocationManager];
#endif
#pragma mark - 逆地理
#if 1
    // 自定义定位
    self.mapView.customizeUserLocationAccuracyCircleRepresentation = YES;
    
    self.mapView.userTrackingMode = MAUserTrackingModeFollow;
#endif
    // 搜索
    [self initSearchBar];
    
    [self updateCourseUI];
    
    [self updateDetailUI];
    
    [self initSearchDisplay];
    // 按钮
    [self createBottomButton];
}

- (void)createBottomButton
{
    self.locationBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.locationBtn setBackgroundImage:[UIImage imageNamed:@"location"] forState:UIControlStateNormal];
    [self.mapView addSubview:self.locationBtn];
    [self.locationBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view).with.offset(10);
        make.bottom.mas_equalTo(self.view).with.offset(-15);
        make.width.mas_equalTo(40);
        make.height.mas_equalTo(40);
    }];
    [self.locationBtn addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
    
    self.busBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.busBtn setBackgroundImage:[UIImage imageNamed:@"bus"] forState:UIControlStateNormal];
    [self.mapView addSubview:self.busBtn];
    [self.busBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.locationBtn.mas_right).with.offset(5);
        make.bottom.mas_equalTo(self.view).with.offset(-15);
        make.width.mas_equalTo(40);
        make.height.mas_equalTo(40);
    }];
    [self.busBtn addTarget:self action:@selector(busAction) forControlEvents:UIControlEventTouchUpInside];
    
    self.poiBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.poiBtn setBackgroundImage:[UIImage imageNamed:@"search"] forState:UIControlStateNormal];
    [self.mapView addSubview:self.poiBtn];
    [self.poiBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.busBtn.mas_right).with.offset(5);
        make.bottom.mas_equalTo(self.view).with.offset(-15);
        make.width.mas_equalTo(40);
        make.height.mas_equalTo(40);
    }];
    [self.poiBtn addTarget:self action:@selector(poiAction) forControlEvents:UIControlEventTouchUpInside];
}

- (void)buttonAction
{
    
    if (self.mapView.userTrackingMode != MAUserTrackingModeFollow)
    {
        [self.mapView setUserTrackingMode:MAUserTrackingModeFollow animated:YES];
        [self.mapView setZoomLevel:15.1 animated:YES];
    }
}

- (void)busAction
{
    self.bus = YES;
    self.searchBar.placeholder = BusLinePlaceHolder;
}

- (void)poiAction
{
    self.bus = NO;
    self.searchBar.placeholder = @"输入关键字搜索";
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    UIView *temp = self.tabBarController.view.subviews[2];
    [UIView animateWithDuration:1 animations:^{
        temp.frame = CGRectMake(0, kScreenHeight, kScreenWidth, 49);
    }];
}

- (MAOverlayView *)mapView:(MAMapView *)mapView viewForOverlay:(id <MAOverlay>)overlay
{
    /* 自定义定位精度对应的MACircleView. */
    if (overlay == mapView.userLocationAccuracyCircle)
    {
        MACircleView *accuracyCircleView = [[MACircleView alloc] initWithCircle:overlay];
        
        accuracyCircleView.lineWidth    = 2.f;
        accuracyCircleView.strokeColor  = [UIColor lightGrayColor];
        accuracyCircleView.fillColor    = [UIColor colorWithRed:1 green:0 blue:0 alpha:.3];
        
        return accuracyCircleView;
    }else if ([overlay isKindOfClass:[MAPolyline class]])
    {
        MAPolylineView *polylineRenderer = [[MAPolylineView alloc] initWithPolyline:overlay];
        
        polylineRenderer.lineWidth   = 4.f;
        polylineRenderer.strokeColor = [UIColor magentaColor];
        
        return polylineRenderer;
    }
    
    return nil;
}

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    /* 自定义userLocation对应的annotationView. */
    if ([annotation isKindOfClass:[MAUserLocation class]])
    {
        static NSString *userLocationStyleReuseIndetifier = @"userLocationStyleReuseIndetifier";
        MAAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:userLocationStyleReuseIndetifier];
        if (annotationView == nil)
        {
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation
                                                             reuseIdentifier:userLocationStyleReuseIndetifier];
        }
        
//        annotationView.image = [UIImage imageNamed:@"userPosition"];
        
        self.userLocationAnnotationView = annotationView;
        
        
        
        return annotationView;
    }else if ([annotation isKindOfClass:[BusStopAnnotation class]])
    {
        static NSString *busStopIdentifier = @"busStopIdentifier";
        
        MANaviAnnotationView *poiAnnotationView = (MANaviAnnotationView*)[self.mapView dequeueReusableAnnotationViewWithIdentifier:busStopIdentifier];
        if (poiAnnotationView == nil)
        {
            poiAnnotationView = [[MANaviAnnotationView alloc] initWithAnnotation:annotation
                                                                reuseIdentifier:busStopIdentifier];
        }
        poiAnnotationView.animatesDrop   = YES;
        poiAnnotationView.canShowCallout = YES;
        poiAnnotationView.draggable      = YES;
        poiAnnotationView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
        poiAnnotationView.rightCalloutAccessoryView.tag = RightCallOutTag;
        //call online navi by left accessory.
        
        poiAnnotationView.leftCalloutAccessoryView.tag  = LeftCallOutTag;
        
        return poiAnnotationView;
    }else if ([annotation isKindOfClass:[AMapTipAnnotation class]])
    {
        static NSString *tipIdentifier = @"tipIdentifier";
        
        MANaviAnnotationView *poiAnnotationView = (MANaviAnnotationView *)[self.mapView dequeueReusableAnnotationViewWithIdentifier:tipIdentifier];
        if (poiAnnotationView == nil)
        {
            poiAnnotationView = [[MANaviAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:tipIdentifier];
        }
        
        poiAnnotationView.animatesDrop   = YES;
        poiAnnotationView.canShowCallout = YES;
        poiAnnotationView.draggable      = YES;
        poiAnnotationView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
        poiAnnotationView.rightCalloutAccessoryView.tag = RightCallOutTag;
        poiAnnotationView.leftCalloutAccessoryView.tag  = LeftCallOutTag;
        return poiAnnotationView;
    }else if ([annotation isKindOfClass:[POIAnnotation class]])
    {
        static NSString *poiIdentifier = @"poiIdentifier";
        MANaviAnnotationView *poiAnnotationView = (MANaviAnnotationView*)[self.mapView dequeueReusableAnnotationViewWithIdentifier:poiIdentifier];
        if (poiAnnotationView == nil)
        {
            poiAnnotationView = [[MANaviAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:poiIdentifier];
        }
        
        poiAnnotationView.animatesDrop   = YES;
        poiAnnotationView.canShowCallout = YES;
        poiAnnotationView.draggable      = YES;
        poiAnnotationView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
        poiAnnotationView.rightCalloutAccessoryView.tag = RightCallOutTag;
        poiAnnotationView.leftCalloutAccessoryView.tag  = LeftCallOutTag;
        return poiAnnotationView;
    }
    
    return nil;
}

- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation
{
    if (!updatingLocation && self.userLocationAnnotationView != nil)
    {
        [UIView animateWithDuration:0.1 animations:^{
            
            double degree = userLocation.heading.trueHeading - self.mapView.rotationDegree;
            self.userLocationAnnotationView.transform = CGAffineTransformMakeRotation(degree * M_PI / 180.f );
            
        }];
    }
}

#pragma mark - Override

- (void)returnAction
{
    [super returnAction];
    
    self.mapView.customizeUserLocationAccuracyCircleRepresentation = NO;
    
    self.mapView.userTrackingMode = MAUserTrackingModeNone;
}

#if 1
#pragma mark - busLine

/* 更新"上一个", "下一个"按钮状态. */
- (void)updateCourseUI
{
    /* 上一个. */
    self.previousItem.enabled = (self.currentIndex > 0);
    
    /* 下一个. */
    self.nextItem.enabled = (self.currentIndex < (NSInteger)self.busLines.count - 1);
}

/* 更新"详情"按钮状态. */
- (void)updateDetailUI
{
    self.detailItem.enabled = self.busLines.count != 0;
}

/* 清空地图上的overlay, annotation. */
- (void)clear
{
    [self.mapView removeOverlays:self.mapView.overlays];
    
    [self.mapView removeAnnotations:self.mapView.annotations];
}

- (AMapBusLine *)currentBusLine
{
    if (self.busLines.count == 0)
    {
        return nil;
    }
    
    if (self.currentIndex < 0 || self.currentIndex >= self.busLines.count)
    {
        return nil;
    }
    
    return self.busLines[self.currentIndex];
}

- (void)presentCurrentBusLine
{
    AMapBusLine *busLine = [self currentBusLine];
    
    if (busLine == nil)
    {
        return;
    }
    
    NSMutableArray *busStopAnnotations = [NSMutableArray array];
    
    [busLine.busStops enumerateObjectsUsingBlock:^(AMapBusStop *busStop, NSUInteger idx, BOOL *stop) {
        BusStopAnnotation *annotation = [[BusStopAnnotation alloc] initWithBusStop:busStop];
        
        [busStopAnnotations addObject:annotation];
    }];
    
    [self.mapView addAnnotations:busStopAnnotations];
    
    MAPolyline *polyline = [CommonUtility polylineForBusLine:busLine];
    
    [self.mapView addOverlay:polyline];
    
    [self.mapView setVisibleMapRect:polyline.boundingMapRect edgePadding:UIEdgeInsetsMake(BusLinePaddingEdge, BusLinePaddingEdge, BusLinePaddingEdge, BusLinePaddingEdge) animated:YES];
}

- (void)gotoDetailForBusLine:(AMapBusLine *)busLine
{
    if (busLine != nil)
    {
        BusLineDetailViewController *busLineDetailViewController = [[BusLineDetailViewController alloc] init];
        
        busLineDetailViewController.busLine = busLine;
        
        [self.navigationController pushViewController:busLineDetailViewController animated:YES];
    }
}

- (void)gotoDetailForBusStop:(AMapBusStop *)busStop
{
    if (busStop != nil)
    {
        BusStopDetailViewController *busStopDetailViewController = [[BusStopDetailViewController alloc] init];
        
        busStopDetailViewController.busStop = busStop;
        
        [self.navigationController pushViewController:busStopDetailViewController animated:YES];
    }
}

/* 根据key搜索公交路线. */
- (void)searchLineByKey:(NSString *)key
{
    if (key.length == 0)
    {
        return;
    }
    
    AMapBusLineNameSearchRequest *line = [[AMapBusLineNameSearchRequest alloc] init];
    line.keywords           = key;
    line.city               = @"dalian";
    line.requireExtension   = YES;
    
    [self.search AMapBusLineNameSearch:line];
}

#pragma mark - AMapSearchDelegate

/* 公交路线回调*/
- (void)onBusLineSearchDone:(AMapBusLineBaseSearchRequest *)request response:(AMapBusLineSearchResponse *)response
{
    if (response.buslines.count != 0)
    {
        [self.busLines setArray:response.buslines];
        self.currentIndex = 0;
        [self updateCourseUI];
        [self updateDetailUI];
        
        [self presentCurrentBusLine];
    }
}

#pragma mark - MAMapViewDelegate

- (void)mapView:(MAMapView *)mapView annotationView:(MAAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
    if ([view.annotation isKindOfClass:[AMapTipAnnotation class]])
    {
        if ([control tag] == RightCallOutTag) {
            [self gotoDetailForTip:[(AMapTipAnnotation *)view.annotation tip]];
        }else if ([control tag] == LeftCallOutTag){
#if 1
            // sdk
            MANaviConfig * config = [[MANaviConfig alloc] init];
            config.destination    = view.annotation.coordinate;
            config.appScheme      = [self getApplicationScheme];
            config.appName        = [self getApplicationName];
            config.strategy       = MADrivingStrategyShortest;
            
            if(![MAMapURLSearch openAMapNavigation:config])
            {
                [MAMapURLSearch getLatestAMapApp];
            }
#endif
#if 0
            CLLocationCoordinate2D location = [view.annotation coordinate];
            [self systemNaviWithlatitude:location.latitude longtitude:location.longitude title:[view.annotation title] subtitle:[view.annotation subtitle]];
#endif
        }
    }
    else if ([view.annotation isKindOfClass:[BusStopAnnotation class]])
    {
        if ([control tag] == RightCallOutTag) {
            
            [self gotoDetailForBusStop:[(BusStopAnnotation*)view.annotation busStop]];
        }else if ([control tag] == LeftCallOutTag){
#if 1
            MANaviConfig * config = [[MANaviConfig alloc] init];
            config.destination    = view.annotation.coordinate;
            NSLog(@"%f%f", config.destination.latitude, config.destination.longitude);
            config.appScheme      = [self getApplicationScheme];
            config.appName        = [self getApplicationName];
            config.strategy       = MADrivingStrategyShortest;
            if(![MAMapURLSearch openAMapNavigation:config])
            {
                [MAMapURLSearch getLatestAMapApp];
            }
#endif
#if 0
            CLLocationCoordinate2D location = [view.annotation coordinate];
            [self systemNaviWithlatitude:location.latitude longtitude:location.longitude title:[view.annotation title] subtitle:[view.annotation subtitle]];
#endif
        }
    }
    else if ([view.annotation isKindOfClass:[POIAnnotation class]])
    {
        if ([control tag] == RightCallOutTag) {
            
            [self gotoDetailForPoi:[(POIAnnotation *)view.annotation poi]];
        }else if ([control tag] == LeftCallOutTag){
#if 1
            MANaviConfig * config = [[MANaviConfig alloc] init];
            config.destination    = view.annotation.coordinate;
            config.appScheme      = [self getApplicationScheme];
            config.appName        = [self getApplicationName];
            config.strategy       = MADrivingStrategyShortest;
            
            if(![MAMapURLSearch openAMapNavigation:config])
            {
                [MAMapURLSearch getLatestAMapApp];
            }
#endif
#if 0
            CLLocationCoordinate2D location = [view.annotation coordinate];
            [self systemNaviWithlatitude:location.latitude longtitude:location.longitude title:[view.annotation title] subtitle:[view.annotation subtitle]];
#endif
        }
    }
}

#pragma mark UISearchBarDelegate

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    [self.searchBar setShowsCancelButton:YES];
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
    [self.searchBar setShowsCancelButton:NO];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [self.searchBar resignFirstResponder];
    [self clear];
    
    if (self.bus) {
        [self.busLines removeAllObjects];
        self.currentIndex = 0;
        
        [self updateCourseUI];
        [self updateDetailUI];
        
        [self searchLineByKey:searchBar.text];
    }else
    {
        NSString *key = searchBar.text;
        /* 按下键盘enter, 搜索poi */
        AMapPOIKeywordsSearchRequest *request = [[AMapPOIKeywordsSearchRequest alloc] init];
        
        request.keywords         = key;
        request.city             = @"0411";
        request.requireExtension = YES;
        [self.search AMapPOIKeywordsSearch:request];
        
        [self.displayController setActive:NO animated:NO];
        
        self.searchBar.placeholder = key;
    }
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [self.searchBar resignFirstResponder];
    self.searchBar.placeholder = @"请输入";
}

#pragma mark - Handle Action

/* 上一条公交路线. */
- (void)previousAction
{
    [self clear];
    
    self.currentIndex--;
    
    [self presentCurrentBusLine];
    
    [self updateCourseUI];
}

/* 下一条公交路线. */
- (void)nextAction
{
    [self clear];
    
    self.currentIndex++;
    
    [self presentCurrentBusLine];
    
    [self updateCourseUI];
}

/* 详情. */
- (void)detailAction
{
    AMapBusLine *busLine = [self currentBusLine];
    
    if (busLine != nil)
    {
        [self gotoDetailForBusLine:busLine];
    }
}

#pragma mark - Initialization

- (void)initSearchBar
{
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectZero];
    self.searchBar.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    self.searchBar.barStyle     = UIBarStyleBlack;
    self.searchBar.delegate     = self;
    self.searchBar.placeholder  = @"请输入";
    self.searchBar.keyboardType = UIKeyboardTypeDefault;
    
    self.navigationItem.titleView = self.searchBar;
    
    [self.searchBar sizeToFit];
}

#pragma mark - Life Cycle

- (id)init
{
    if (self = [super init])
    {
        self.busLines = [NSMutableArray array];
         self.tips = [NSMutableArray array];
    }
    
    return self;
}


#endif
#if 1
#pragma mark - POI
/* 输入提示 搜索.*/
- (void)searchTipsWithKey:(NSString *)key
{
    if (key.length == 0)
    {
        return;
    }
    
    AMapInputTipsSearchRequest *tips = [[AMapInputTipsSearchRequest alloc] init];
    tips.keywords = key;
    tips.city     = @"大连";
    
    [self.search AMapInputTipsSearch:tips];
}
- (void)clearAndShowAnnotationWithTip:(AMapTip *)tip
{
    /* 清除annotations & overlays */
    [self clear];
    
    if (tip.uid != nil && tip.location != nil) /* 可以直接在地图打点  */
    {
        AMapTipAnnotation *annotation = [[AMapTipAnnotation alloc] initWithMapTip:tip];
        [self.mapView addAnnotation:annotation];
        [self.mapView setCenterCoordinate:annotation.coordinate];
        [self.mapView selectAnnotation:annotation animated:YES];
    }
    else if (tip.uid != nil && tip.location == nil)/* 公交路线，显示出来*/
    {
        AMapBusLineIDSearchRequest *request = [[AMapBusLineIDSearchRequest alloc] init];
        request.city                        = @"北京";
        request.uid                         = tip.uid;
        request.requireExtension            = YES;
        
        [self.search AMapBusLineIDSearch:request];
    }
    else if(tip.uid == nil && tip.location == nil)/* 品牌名，进行POI关键字搜索 */
    {
        AMapPOIKeywordsSearchRequest *request = [[AMapPOIKeywordsSearchRequest alloc] init];
        
        request.keywords         = tip.name;
        request.city             = @"010";
        request.requireExtension = YES;
        [self.search AMapPOIKeywordsSearch:request];
    }
}

- (void)gotoDetailForTip:(AMapTip *)tip
{
    if (tip != nil)
    {
        TipDetailViewController *tipDetailViewController = [[TipDetailViewController alloc] init];
        tipDetailViewController.tip                      = tip;
        
        [self.navigationController pushViewController:tipDetailViewController animated:YES];
    }
}

- (void)gotoDetailForPoi:(AMapPOI *)poi
{
    if (poi != nil)
    {
        PoiDetailViewController *detail = [[PoiDetailViewController alloc] init];
        detail.poi                      = poi;
        
        [self.navigationController pushViewController:detail animated:YES];
    }
}

/* 输入提示回调. */
- (void)onInputTipsSearchDone:(AMapInputTipsSearchRequest *)request response:(AMapInputTipsSearchResponse *)response
{
    [self.tips setArray:response.tips];
    
    [self.displayController.searchResultsTableView reloadData];
}

/* POI 搜索回调. */
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response
{
    if (response.pois.count == 0)
    {
        return;
    }
    
    NSMutableArray *poiAnnotations = [NSMutableArray arrayWithCapacity:response.pois.count];
    
    [response.pois enumerateObjectsUsingBlock:^(AMapPOI *obj, NSUInteger idx, BOOL *stop) {
        
        [poiAnnotations addObject:[[POIAnnotation alloc] initWithPOI:obj]];
        
    }];
    
    /* 将结果以annotation的形式加载到地图上. */
    [self.mapView addAnnotations:poiAnnotations];
    
    /* 如果只有一个结果，设置其为中心点. */
    if (poiAnnotations.count == 1)
    {
//        AMapNaviPoint *navipoint = poiAnnotations.lastObject;
//        CLLocationCoordinate2D center = CLLocationCoordinate2DMake(navipoint.latitude, navipoint.longitude);
//        [self.mapView setCenterCoordinate:[[poiAnnotations lastObject] coordinate] animated:YES];
//        CLLocationCoordinate2D center = (CLLocationCoordinate2D)[poiAnnotations[0] coordinate];
    }
    /* 如果有多个结果, 设置地图使所有的annotation都可见. */
    else
    {
        [self.mapView showAnnotations:poiAnnotations animated:NO];
    }
}

#pragma mark - UISearchDisplayDelegate

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    [self searchTipsWithKey:searchString];
    
    return YES;
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.tips.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *tipCellIdentifier = @"tipCellIdentifier";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:tipCellIdentifier];
    
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                      reuseIdentifier:tipCellIdentifier];
        cell.imageView.image = [UIImage imageNamed:@"locate"];
    }
    
    AMapTip *tip = self.tips[indexPath.row];
    
    if (tip.location == nil)
    {
        cell.imageView.image = [UIImage imageNamed:@"search"];
    }
    
    cell.textLabel.text = tip.name;
    cell.detailTextLabel.text = tip.district;
    
    return cell;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    AMapTip *tip = self.tips[indexPath.row];
    
    [self clearAndShowAnnotationWithTip:tip];
    
    [self.displayController setActive:NO animated:NO];
    
    self.searchBar.placeholder = tip.name;
}

- (void)initSearchDisplay
{
    self.displayController = [[UISearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self];
    self.displayController.delegate                = self;
    self.displayController.searchResultsDataSource = self;
    self.displayController.searchResultsDelegate   = self;
//    self.displayController.searchContentsController.edgesForExtendedLayout = UIRectEdgeNone;
}

#endif
#pragma mark - 系统导航
- (void)systemNaviWithlatitude:(CGFloat)latitude longtitude:(CGFloat)longtitude title:(NSString *)title subtitle:(NSString *)subtitle
{
    HZL_MapViewController *hzl = [[HZL_MapViewController alloc] init];
    hzl.name = title;
    hzl.add = subtitle;
    hzl.latitude = [NSString stringWithFormat:@"%f", latitude];
    hzl.longitude = [NSString stringWithFormat:@"%f", longtitude];
    [self.navigationController pushViewController:hzl animated:YES];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    //    [self.locationManager startUpdatingLocation];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController setToolbarHidden:YES animated:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - busSearch
//- (void)rightAction
//{
//    BusLineViewController *busVC = [[BusLineViewController alloc] init];
//    [self.navigationController pushViewController:busVC animated:YES];
//}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
